#include <stdio.h>
#include "../include/login.h"//登录系统
#include "../include/password.h"
#include "../include/log.h"

//接收方
#define get_piv "192.168.0.161"
#define get_port 6666
extern TRAN m_node;
int main(){
	char logbuf[128];
	//创建TCP类型套接字
	int client_socket=socket(AF_INET,SOCK_STREAM,0);
	
	//向服务端发起连接请求
	struct sockaddr_in saddr;
	saddr.sin_family = AF_INET;
	saddr.sin_port = htons(get_port);//port 
	saddr.sin_addr.s_addr = inet_addr(get_piv);//ip
	int isok = connect(client_socket,(struct sockaddr*)&saddr,sizeof(saddr));
	if(isok == -1)
	{
		strcpy(logbuf,"connect异常");
		logadd(logbuf);
		perror("connect");	
		return -1;
	}
	printf("已成功与服务器建立连接\n");
	strcpy(logbuf,"成功与服务器建立连接");
	logadd(logbuf);
	
	//将文件描述符改为非阻塞状态便于read使用
	int flags, s;
	// 获取当前的文件状态标志
	flags = fcntl(client_socket,F_GETFL,0);
	if (flags == -1) {
		strcpy(logbuf,"fcntl异常");
		logadd(logbuf);
		perror("fcntl F_GETFL");
		
		printf("客户端退出\n");	
		close(client_socket);
		sprintf(logbuf,"客户端退出\n");
		logadd(logbuf);
		return -1;
	}
	// 添加O_NONBLOCK标志
	flags |= O_NONBLOCK;
	// 设置新的文件状态标志
	s = fcntl(client_socket,F_SETFL,flags);
	if (s == -1) {
		perror("fcntl F_SETFL");
		
		printf("客户端退出\n");	
		close(client_socket);
		sprintf(logbuf,"客户端退出\n");
		logadd(logbuf);
		return -1;
	}
	
	
	//system("clear");//清空
	int sel = 0;
	int flag=-1;
	while(1){
		printf("1:登录\n2:注册\n3:退出\n");
		scanf("%d",&sel);
		if(sel!=1 && sel!=2){
			break;
		}
		flag = client_login(sel,client_socket);//登录/注册
		if(flag==0||flag==1){
			if(sel==1){
				sprintf(logbuf,"用户:%s登录成功,权限为:%d",m_node.name,flag);
				logadd(logbuf);
				printf("登录成功,用户权限为:%d\n",flag);
				m_node.perm=flag;
				break;
			}else if(sel==2){
				sprintf(logbuf,"成功注册用户为:%s",m_node.name);
				logadd(logbuf);
				puts("注册成功,请重新登录");
				continue;
			}
		}else{
			puts("用户名或密码错误,请重新输入");
			continue;
		}
	}
	while(1){
		printf("1:账号管理\n2:设备监测\n3:退出\n");
		scanf("%d",&sel);
		if(sel!=1 && sel!=2){
			break;
		}
		switch(sel){
			case 1:
				flag = use_system(client_socket);
				if(flag==1){
					sprintf(logbuf,"成功修改密码为:%s\n客户端退出\n",m_node.pas);
					logadd(logbuf);
					puts("密码修改成功,请重新登录\n");
					printf("客户端退出\n");	
					close(client_socket);
					return 0;
				}else if(flag==2){
					sprintf(logbuf,"成功账户注销\n客户端退出\n");
					logadd(logbuf);
					puts("账户已注销,即将退出\n");
					printf("客户端退出\n");	
					close(client_socket);
					return 0;
				}
				break;
			case 2:
				//flag == device_system(client_socket);
				break;
		}
	}
	printf("客户端退出\n");	
	close(client_socket);
	sprintf(logbuf,"客户端退出\n");
	logadd(logbuf);
	return 0;
}